package com.corpcredit.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.security.GrantedAuthority;

/**
 * This class is used to represent available authorities in the database.
 * 
 * @author Zhao
 */
@Entity
@Table(name = "permission")
public class Permission extends BaseObject implements Serializable,
        GrantedAuthority
{
    private Long id;
    private String name;
    private String description;

    public Permission()
    {
    }

    public Permission( final String name )
    {
        super();
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId()
    {
        return id;
    }

    public void setId( Long id )
    {
        this.id = id;
    }

    @Column(length = 20)
    public String getName()
    {
        return name;
    }

    public void setName( String name )
    {
        this.name = name;
    }

    @Column(length = 64)
    public String getDescription()
    {
        return description;
    }

    public void setDescription( String description )
    {
        this.description = description;
    }

    /*
     * @see org.acegisecurity.GrantedAuthority#getAuthority() @return the name
     *      property (getAuthority required by Acegi's GrantedAuthority
     *      interface)
     */
    @Transient
    public String getAuthority()
    {
        return name;
    }

    /**
     * {@inheritDoc}
     */
    public boolean equals( Object o )
    {
        if( this == o )
        {
            return true;
        }
        if( !(o instanceof Permission) )
        {
            return false;
        }

        final Permission authority = (Permission) o;

        return !(name != null ? !name.equals( authority.name )
                : authority.name != null);

    }

    /**
     * {@inheritDoc}
     */
    public int hashCode()
    {
        return (name != null ? name.hashCode() : 0);
    }

    /**
     * {@inheritDoc}
     */
    public String toString()
    {
        return new ToStringBuilder( this, ToStringStyle.SIMPLE_STYLE ).append( this.name )
                                                                      .toString();
    }

    public int compareTo( Object o )
    {
        return (equals( o ) ? 0 : -1);
    }
}
